/**
 * 认证状态管理模块
 * 处理登录、登出、Token管理
 */

import { defineStore } from 'pinia'
import { login, getUserInfo } from '@/services/auth'
import type { UserInfo } from '@/store/types/user'

interface AuthState {
  token: string | null
  userInfo: UserInfo
  isLogin: boolean
  permissions: string[]
}

export const useAuthStore = defineStore('auth', {
  state: (): AuthState => ({
    token: localStorage.getItem('token'),
    userInfo: { id: 0, username: '', nickname: '', avatar: '' },
    isLogin: !!localStorage.getItem('token'),
    permissions: [],
  }),

  getters: {
    // 是否已登录
    isLoggedIn: state => state.isLogin || !!state.token,

    // 用户名
    username: state => state.userInfo.username || '',

    // 用户显示名
    displayName: state => state.userInfo.nickname || state.userInfo.username || '',

    // 是否有权限
    hasPermission: state => (permission: string) => {
      return state.permissions.includes(permission)
    },
  },

  actions: {
    // 登录
    async login(credentials: {
      username: string
      password: string
      captcha?: string
      captchaId?: string
      captcha_token?: string
    }) {
      try {
        const res = await login(credentials as any)

        if (res.data && res.data.token) {
          this.token = res.data.token
          this.userInfo = {
            id: res.data.user_info?.id || 0,
            username: res.data.user_info?.username || '',
            nickname: res.data.user_info?.name || res.data.user_info?.username || '',
            avatar: res.data.user_info?.avatar || '',
            department: (res.data.user_info as any)?.department,
            position: (res.data.user_info as any)?.position,
            create_time: (res.data.user_info as any)?.create_time,
            menu: (res.data as any).menu,
          }
          this.isLogin = true

          // 保存到 localStorage
          localStorage.setItem('token', res.data.token)
          localStorage.setItem('userInfo', JSON.stringify(this.userInfo))

          return res
        } else {
          throw new Error('Token not provided in response')
        }
      } catch (error) {
        throw error
      }
    },

    // 获取用户信息
    async fetchUserInfo() {
      try {
        // 先从 localStorage 恢复
        const cachedUserInfo = localStorage.getItem('userInfo')
        if (cachedUserInfo) {
          try {
            const userInfoObj = JSON.parse(cachedUserInfo)
            if (userInfoObj && userInfoObj.id > 0) {
              this.userInfo = userInfoObj
              return { code: 0, msg: 'success', data: { admin: userInfoObj } }
            }
          } catch (e) {
            localStorage.removeItem('userInfo')
          }
        }

        // 从服务器获取
        const res = await getUserInfo()
        if (res.code === 0) {
          const adminInfo = res.data.admin
          this.userInfo = {
            id: adminInfo?.id || 0,
            username: adminInfo?.username || '',
            nickname: adminInfo?.name || adminInfo?.username || '',
            avatar: adminInfo?.thumb || adminInfo?.avatar || '',
            department: (adminInfo as any)?.department || (adminInfo as any)?.department_names,
            position: (adminInfo as any)?.position || (adminInfo as any)?.position_name,
            create_time: adminInfo?.create_time,
            menu: res.data.menu,
          }

          localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
        }
        return res
      } catch (error: any) {
        // 如果是401错误，清除本地状态
        if (error.response?.status === 401) {
          this.logout()
        }
        throw error
      }
    },

    // 登出
    logout() {
      this.token = null
      this.userInfo = { id: 0, username: '', nickname: '', avatar: '' }
      this.isLogin = false
      this.permissions = []

      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    },

    // 设置Token
    setToken(token: string) {
      this.token = token
      localStorage.setItem('token', token)
    },

    // 设置用户信息
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
  },
})
